package com.ebelter.scaleblesdk.ble.bluetooth;


import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothProfile;
import android.content.Context;

import com.ebelter.scaleblesdk.ble.bluetooth.device.AbstractDeviceDataHandle;
import com.ebelter.scaleblesdk.util.ULog;

import java.util.UUID;

/**
 * 蓝牙消息监听类-autogatt连接方式
 * @author fenghui
 *
 */
@SuppressLint("NewApi")
public class BtAutoGattListener extends BlueToothMessageListener {
	private static final String TAG = "BtAutoGattListener";
	boolean isNeedReconnect = false;

	public BtAutoGattListener(Context ctx, AbstractDeviceDataHandle deviceDataHandlerArg) {
		super(ctx, deviceDataHandlerArg);

		//连接回调信息
		mGattCallback = new BluetoothGattCallback() {
			@Override
			public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
				mHandler.removeCallbacks(connectTimeoutThread);
				ULog.i(TAG, "onConnectionStateChange, status:" + status + ",new status:" + newState);
				if(status == BluetoothGatt.GATT_SUCCESS) {

					if (newState == BluetoothProfile.STATE_CONNECTED) {
						if(!isConnected) {
							//连接状态改变为连接成功
							mBluetoothGatt.discoverServices();
						}
					} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
						if(isConnected) {
							ULog.i(TAG, "device disconnected.");
							isConnected = false;
							lastRssi = 0;
							deviceDataHandler.getMsgCallBack().onDisConnected();
						}

						if(isNeedReconnect) {
							isNeedReconnect = false;
							gatt.close();
							if(isNeedConnecting) {
								startScanDevice();
							}
						}
					}
				} else {
					ULog.e(TAG, "status is not 0. do close operate.");
					gatt.close();
					mBluetoothGatt = null;
					isConnected = false;
					if(isNeedConnecting) {
						startScanDevice();
					}
				}
			}

			@Override
			public void onServicesDiscovered(BluetoothGatt gatt, int status) {
				ULog.w(TAG, "onServicesDiscovered received: " + status);
				if (status == BluetoothGatt.GATT_SUCCESS) {

					//搜寻设备完毕，写入数据特征到设备中
					isConnected = true;
					if (mBluetoothAdapter == null || mBluetoothGatt == null) {
						ULog.e(TAG, "BluetoothAdapter not initialized");
						return;
					}

					btService = mBluetoothGatt.getService(UUID.fromString(BluetoothUtil.getDeviceServiceUUID()));
					if(btService == null) {
						ULog.e(TAG, "service is null.");
						//状态码出错，先断开连接然后再重新连接
						gatt.disconnect();
						gatt.close();
						return;
					}

					//数据通知uuid列表
					deviceReadNotifyUUIDs = BluetoothUtil.getReadUUIDs();
					BluetoothGattCharacteristic characteristic = btService.getCharacteristic(UUID.fromString(deviceReadNotifyUUIDs[0]));
					if(characteristic != null) {
						mBluetoothGatt.setCharacteristicNotification(characteristic, true);
						BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(BluetoothUtil.CLIENT_CHARACTERISTIC_CONFIG));
						if(descriptor != null) {
							ULog.i(TAG, "mBluetoothGatt.writeDescriptor.");
							descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
							mBluetoothGatt.writeDescriptor(descriptor);
						} else {
							ULog.e(TAG, "descriptor is null.");
						}
						mBluetoothGatt.readCharacteristic(characteristic);
					}

				} else {
					//异常状态，比如129，需要重新连接设备
					isNeedReconnect = true;
					gatt.disconnect();
				}
			}


			public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor gattDescriptor, int status) {
				ULog.i(TAG, "onDescriptorWrite, status:" + status);
				if(status != 0) {
					ULog.i(TAG, "onDescriptorWrite, status not 0, do disconnect.");
					//状态码出错，先断开连接然后再重新连接
					//异常状态，比如129，重启蓝牙
					isNeedReconnect = true;
					gatt.disconnect();
				} else {
					//这里通知前端，设备连接成功
					deviceDataHandler.getMsgCallBack().onDeviceConnected();

					connectTotal++;
					ULog.i(TAG, "device connected times." + connectTotal
							+ ",isConnected:" + isConnected);
				}

			};

			@Override
			public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
				//读取到数据
				ULog.i(TAG, "onCharacteristicRead");
				if (status == BluetoothGatt.GATT_SUCCESS) {
					ULog.i("TAG", characteristic.getValue().toString());
				}
			}

			/**
			 * 返回数据。
			 */
			@Override
			public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
				currMutualTime = System.currentTimeMillis();
				ULog.i("onCharacteristicChanged---------", "isConnected:" + isConnected);
				if(!isConnected) {
					ULog.e(TAG, "device not connected, return from onCharacteristicChanged.");
					return;
				}
				// 数据
				StringBuilder dataSb = new StringBuilder();
				for (int i = 0, len = characteristic.getValue().length; i < len; i++) {
					dataSb.append(Integer.toHexString(characteristic.getValue()[i] & 0xff));
					dataSb.append(" ");
				}
				ULog.i(TAG, "receive device data:" + dataSb.toString());
				deviceDataHandler.handlerData(characteristic.getValue(), dataSb.toString());
			}
		};
	}


	/**
	 * 开始连接设备
	 */
	@Override
	public void startConnectDevice(BluetoothDevice device) {
		isNeedConnecting = true;
		currConnectDevice = device;
		deviceDataHandler.setDeviceAddress(device.getAddress());
		if(!isConnected) {
			mBluetoothGatt = currConnectDevice.connectGatt(mContext, true, mGattCallback);
			refreshDeviceCache(mBluetoothGatt);
		}
	}
} 